package it.secse.idmadaption.plugin;

import it.secse.idmadaption.exception.PluginRuleNotFoundException;
import it.secse.idmadaption.util.Constants;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import javax.xml.namespace.QName;

public class PluginFactory {
	
	public static AbstractPlugin getPlugin(String policyType) throws PluginRuleNotFoundException {
		

		StAXOMBuilder builder;
		try {						
			builder = new StAXOMBuilder(Constants.DEFAULT_DIR + File.separator + Constants.RULES_FILE);
			OMElement rulesDocument = builder.getDocumentElement();
			Iterator it1 = rulesDocument.getChildElements();
			while (it1.hasNext()) {
				OMElement rule = (OMElement) it1.next();
				if (rule.getLocalName().equals("policyRule")) {
					if (rule.getFirstChildWithName(new QName("policyType")).getText().trim().equals(policyType)) {
						String className = rule.getFirstChildWithName(new QName("class")).getText().trim();
						AbstractPlugin plug = (AbstractPlugin) Class.forName(className).newInstance();
						return plug;
					}
					
				}
				
			}
			throw new PluginRuleNotFoundException();
			
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		
		return null;
	}

}
